package me.zxk.qwert_poetry.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import me.zxk.qwert_poetry.dao.User;
import me.zxk.qwert_poetry.dto.SimpleUserDTO;
import me.zxk.qwert_poetry.dto.request.UserLoginDTO;
import me.zxk.qwert_poetry.dto.request.UserProfileEditDTO;
import me.zxk.qwert_poetry.dto.request.UserRegisterDTO;
import me.zxk.qwert_poetry.dto.response.LoginResponseDTO;
import me.zxk.qwert_poetry.dto.response.Response;
import me.zxk.qwert_poetry.service.UserService;
import me.zxk.qwert_poetry.util.ApiException;
import me.zxk.qwert_poetry.util.UserContextHolder;
import me.zxk.qwert_poetry.util.VerifyToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户接口")
@RestController
public class UserController {
    private final int ERR_MISSING_PARAM = 2000;

    @Autowired
    private UserService userService;

    @PostMapping("/api/user/register")
    public Response<User> register(@RequestBody UserRegisterDTO dto) {
        User user = new User();
        user.setNickname(dto.getNickname());
        user.setEmail(dto.getEmail());
        user.setPasswordHash(dto.getPassword());
        user.setPhoneNumber(dto.getPhoneNumber());
        user.setRole(User.ROLE_NORMAL);
        return Response.ok(userService.register(user));
    }

    @PostMapping("/api/user/login")
    public Response<LoginResponseDTO> login(@RequestBody UserLoginDTO dto) {
        User user = new User();
        user.setEmail(dto.getEmail());
        user.setPasswordHash(dto.getPassword());
        String token = userService.loginByEmail(user);
        User userInDb = userService.getUserByEmail(dto.getEmail());
        return Response.ok(LoginResponseDTO.fromEntity(userInDb, token));
    }

    @PostMapping("/api/user/update_profile")
    @VerifyToken
    public Response<SimpleUserDTO> updateProfile(@RequestBody UserProfileEditDTO dto) {
        User user = UserContextHolder.getUserContext().getUser();
        user.setNickname(dto.getNickname());
        user.setPhoneNumber(dto.getPhoneNumber());
        user.setRole(dto.getRole());
        user.setEmail(dto.getEmail());
        return Response.ok(SimpleUserDTO.fromEntity(userService.updateProfile(user)));
    }

    @GetMapping("/api/user/get")
    public Response<User> getUserById(@RequestParam Integer id) {
        if (id != null) {
            return Response.ok(userService.getUserById(id));
        }  else {
            throw new ApiException("id is required.", ERR_MISSING_PARAM);
        }
    }

    @PostMapping("/api/user/delete")
    @VerifyToken
    public Response<Void> deleteUserById() {
        int id = UserContextHolder.getUserContext().getUser().getId();
        userService.deleteUserById(id);
        return Response.ok();
    }

}
